Ext.define('App.ux.CodeGen', {
    fileNames: ["Form", "Grid", "SearchForm", "Toolbar", "ViewModel", "Window", "WindowAdd", "WindowEdit"],
    value: '',//填写参数对象
    fields: [],
    packAllName: '',
    dataName: '',
    name: '',
    className: '',
    xtypeName: '',
    formAllName: '',
    formName: '',
    formXtype: '',
    gridAllName: '',
    gridName: '',
    gridXtype: '',
    editGridAllName: '',
    editGridName: '',
    editGridXtype: '',
    searchFormAllName: '',
    searchFormName: '',
    searchFormXtype: '',
    toolbarAllName: '',
    toolbarName: '',
    toolbarXtype: '',
    viewModelAllName: '',
    viewModelName: '',
    viewModelXtype: '',
    windowAllName: '',
    windowName: '',
    windowXtype: '',
    windowAddAllName: '',
    windowAddName: '',
    windowAddXtype: '',
    windowEditAllName: '',
    windowEditName: '',
    windowEditXtype: '',
    datasName:'',
    tab1: "    ",
    tab2: "        ",
    tab3: "            ",
    tab4: "                ",
    init: function (name, fieldstr) {
        this.name = name;
        this.createFields(fieldstr);
        this.initName();
    },
    createRequires: function (codes) {
        var tab1 = this.tab1, tab2 = this.tab2;
        var temp = '', name = this.name;
        codes.push(tab1 + 'requires: [ ');
        for (var i = 0; i < this.fileNames.length; i++) {
            if (i == this.fileNames.length - 1) {
                temp = '"' + name + this.fileNames[i] + '"'
            } else {
                temp = '"' + name + this.fileNames[i] + '",'
            }
            codes.push(tab2 + temp);
        }
        codes.push(tab1 + '],');
    },
    createMainItems: function (codes) {
        var tab1 = this.tab1, tab2 = this.tab2, hideSearch = false, hideToolbar = false;
        if (this.value.hideMainSearch) {
            hideSearch = true;
        }
        if (this.value.hideMainToolbar) {
            hideToolbar = true;
        }
        codes.push(tab1 + 'items: [');
        codes.push(tab2 + "{xtype: '" + this.searchFormXtype + "',hidden: " + hideSearch + "},");
        codes.push(tab2 + "{xtype: '" + this.toolbarXtype + "',hidden: " + hideToolbar + "},");
        codes.push(tab2 + "{xtype: '" + this.gridXtype + "', flex: 1}");
        codes.push(tab1 + "],");
    },
    createMainListeners: function (codes) {
        var tab1 = "    ", tab2 = "        ", tab3 = "            ";
        codes.push(tab1 + 'listeners: {');
        codes.push(tab2 + 'beforerender: function (th) {');
        codes.push(tab3 + "var toolbar = th.down('" + this.toolbarXtype + "');");
        codes.push(tab3 + "var form = th.down('" + this.searchFormXtype + "');");
        codes.push(tab3 + "var grid = th.down('" + this.gridXtype + "');");
        codes.push(tab3 + "form._targetObject = grid;//给查询框关联操作对象");
        codes.push(tab3 + "toolbar._targetObject = grid;//给工具栏添加操作对象");
        codes.push(tab2 + '}');
        codes.push(tab1 + '}');
    },
    initName: function () {
        var temp, name = this.name;
        var cNames = name.split('.');

        var packName = '', packAllName = '';
        for (var i = 0; i < cNames.length; i++) {
            if (i > 1 && i < cNames.length - 1) {
                packName = packName + cNames[i];
            }
            if (i == 0) {
                packAllName = cNames[i];
            } else if (i < cNames.length - 1) {
                packAllName = packAllName + '.' + cNames[i];
            }
        }

        this.packAllName = packAllName;
        var cName = cNames[cNames.length - 1];
        this.className = cName;
        this.dataName = packAllName + '.Datas.' + this.className;
        this.xtypeName = packName + cName;

        //生成form的类全名、类名、xtype名
        this.formAllName = name + 'Form';
        temp = this.formAllName.split('.');
        temp = temp[temp.length - 1];
        this.formName = temp;
        this.formXtype = packName + temp;

        //生成grid的类全名、类名、xtype名
        this.gridAllName = name + 'Grid';
        temp = this.gridAllName.split('.');
        temp = temp[temp.length - 1];
        this.gridName = temp;
        this.gridXtype = packName + temp;
        //生成EditGrid
        this.editGridAllName = name + 'EditGrid';
        temp = this.editGridAllName.split('.');
        temp = temp[temp.length - 1];
        this.editGridName = temp;
        this.editGridXtype = packName + temp;

        //生成searchForm的类全名、类名、xtype名
        this.searchFormAllName = name + 'SearchForm';
        temp = this.searchFormAllName.split('.');
        temp = temp[temp.length - 1];
        this.searchFormName = temp;
        this.searchFormXtype = packName + temp;

        //生成toolbar的类全名、类名、xtype名
        this.toolbarAllName = name + 'Toolbar';
        temp = this.toolbarAllName.split('.');
        temp = temp[temp.length - 1];
        this.toolbarName = temp;
        this.toolbarXtype = packName + temp;

        //生成toolbar的类全名、类名、xtype名
        this.viewModelAllName = name + 'ViewModel';
        temp = this.viewModelAllName.split('.');
        temp = temp[temp.length - 1];
        this.viewModelName = temp;
        this.viewModelXtype = packName + temp;

        //生成window的类全名、类名、xtype名
        this.windowAllName = name + 'Window';
        temp = this.windowAllName.split('.');
        temp = temp[temp.length - 1];
        this.windowName = temp;
        this.windowXtype = packName + temp;

        //生成windowAdd的类全名、类名、xtype名
        this.windowAddAllName = name + 'WindowAdd';
        temp = this.windowAddAllName.split('.');
        temp = temp[temp.length - 1];
        this.windowAddName = temp;
        this.windowAddXtype = packName + temp;

        //生成windowAdd的类全名、类名、xtype名
        this.windowEditAllName = name + 'WindowEdit';
        temp = this.windowEditAllName.split('.');
        temp = temp[temp.length - 1];
        this.windowEditName = temp;
        this.windowEditXtype = packName + temp;

        //生成Datas的类全名
        this.datasName = packAllName + '.Datas';

    },
    main: function () {
        var tab1 = "    ";
        var codes = [], name = this.name;
        codes.push('Ext.define("' + name + '", { ');
        codes.push(tab1 + "extend: 'App.ux.BasePanel',");
        codes.push(tab1 + "xtype: '" + this.xtypeName + "',");
        this.createRequires(codes);
        codes.push(tab1 + "viewModel: '" + this.viewModelXtype + "',");
        codes.push(tab1 + "layout: {type: 'vbox',align: 'stretch'},");
        this.createMainItems(codes);
        this.createMainListeners(codes);
        codes.push('});');

        return codes;
    },
    getPropString: function (data) {
        var propString = '';
        propString = 'name:"' + data.name + '",';
        if (data.component) {
            propString += 'xtype:"' + data.component + '",';
        }
        if (data.flex) {
            propString += 'flex:' + data.flex + ',';
        }
        if (data.length) {
            propString += 'maxLength:' + data.length + ',';
        }
        if (data.width) {
            propString += 'width:' + data.width + ',';
        }
        if (data.hidden) {
            propString += 'hidden:' + data.hidden + ',';
        }
        if (data.code) {
            propString += data.code;
        }
        if (propString.charAt(propString.length - 1) === ',') {
            propString = propString.substring(0, propString.length - 1);
        }
        return propString;
    },
    addCompToForm: function (fields, codes, tab3, tab4) {
        var group = '';
        for (var i = 0; i < fields.length; i++) {
            if (i === 0) {
                codes.push(tab3 + '[');
                group = fields[i].group;
                codes.push(tab4 + "{" + this.getPropString(fields[i]) + "}");
            } else if (group !== fields[i].group || !fields[i].group) {
                codes.push(tab3 + '],');
                codes.push(tab3 + '[');
                group = fields[i].group;
                codes.push(tab4 + "{" + this.getPropString(fields[i]) + "}");
            } else {
                codes.push(tab4 + ",{" + this.getPropString(fields[i]) + "}");
            }
            if (i == fields.length - 1) {
                codes.push(tab3 + ']');
                continue;
            }
        }
    },
    addCompToSearchForm: function (fields, codes, tab3, tab4) {
        var group = '';
        for (var i = 0; i < fields.length; i++) {
            if (i === 0) {
                codes.push(tab3 + '[');
                group = fields[i].group;
                codes.push(tab4 + "{" + this.getPropString(fields[i]) + "}");
            } else if (group !== fields[i].group || !fields[i].group) {
                codes.push(tab3 + '],');
                codes.push(tab3 + '[');
                group = fields[i].group;
                codes.push(tab4 + "{" + this.getPropString(fields[i]) + "}");
            } else {
                codes.push(tab4 + ",{" + this.getPropString(fields[i]) + "}");
            }
            if (i == fields.length - 1) {
                codes.push(tab3 + ',"sr"]');
            }
        }
    },
    createFormComp: function (codes) {
        var tab3 = this.tab3, tab4 = this.tab4;
        var fields = this.fields;
        if (this.value.mainFromConfig && this.value.mainFromConfig.length > 0) {
            fields = this.value.mainFromConfig;
        }
        /*codes.push(tab3 + '[');
        codes.push(tab4 + "{name: 'id',hidden:true}");
        codes.push(tab3 + '],');*/
        this.addCompToForm(fields, codes, tab3, tab4);

    },
    form: function () {
        var tab1 = this.tab1, tab2 = this.tab2;
        var codes = [], name = this.formAllName;
        codes.push('Ext.define("' + name + '", { ');
        codes.push(tab1 + 'extend: "App.view.common.Form",');
        codes.push(tab1 + "xtype: '" + this.formXtype + "',");
        codes.push(tab1 + '_mainConfs: ' + this.dataName + ',');
        codes.push(tab1 + 'defaults: {flex: 1},');
        codes.push(tab1 + '_validator: {//数据的验证，最大值，最小值在这里配置');
        codes.push(tab2 + '//orgName: {allowBlank: false}');
        codes.push(tab1 + '},');
        codes.push(tab1 + '_confs: {');
        codes.push(tab2 + 'components: [//表单字段在这里配置');
        this.createFormComp(codes);
        codes.push(tab2 + ']');
        codes.push(tab1 + '}');
        codes.push('});');
        return codes;

    },
    createGridColumns: function (codes) {
        var tab3 = this.tab3;
        var cols = this.fields;
        if (this.value.mainGridConfig && this.value.mainGridConfig.length > 0) {
            cols = this.value.mainGridConfig;
        }
        for (var i = 0; i < cols.length; i++) {
            if (i === cols.length - 1) {
                codes.push(tab3 + "{" + this.getGridPropString(cols[i]) + "}");
                continue;
            }
            codes.push(tab3 + "{" + this.getGridPropString(cols[i]) + "},");
        }
    },
    getGridPropString: function (data) {
        var propString = '';
        propString = 'name:"' + data.name + '",';

        if (data.flex) {
            propString += 'flex:' + data.flex + ',';
        }
        if (data.width) {
            propString += 'width:' + data.width + ',';
        }
        if (data.hidden) {
            propString += 'hidden:' + data.hidden + ',';
        }
        if (data.code) {
            propString += data.code;
        }
        if (propString.charAt(propString.length - 1) === ',') {
            propString = propString.substring(0, propString.length - 1);
        }
        return propString;
    },
    grid: function () {
        var tab1 = this.tab1, tab2 = this.tab2;
        var codes = [], name = this.gridAllName;
        codes.push('Ext.define("' + name + '", { ');
        codes.push(tab1 + 'extend: "App.view.common.CRUDGrid",');
        codes.push(tab1 + "xtype: '" + this.gridXtype + "',");
        codes.push(tab1 + '_mainConfs: ' + this.dataName + ',');
        codes.push(tab1 + "url:'" + this.value.searchUrl + "',//grid的查询地址");
        codes.push(tab1 + '_confs: {// 配置grid的columns,支持原生columns的所有写法');
        codes.push(tab2 + 'columns: [');
        this.createGridColumns(codes);
        codes.push(tab2 + ']');
        codes.push(tab1 + '}');

        codes.push('});');

        return codes;
    },
    createDatas:function () {
        var tab1 = this.tab1, tab2 = this.tab2;
        var tab3 = this.tab3;
        var codes = [];
        codes.push('Ext.define("' + this.datasName + '", { ');
        codes.push(tab1 + "statics: {");
        codes.push(tab2 + this.className +': [');
        for (var i = 0; i < this.fields.length; i++) {
            if(i === 0){
                codes.push(tab3 + JSON.stringify(this.fields[i]));
            }else {
                codes.push(tab3 +','+ JSON.stringify(this.fields[i]));
            }

        }
        codes.push(tab2 + ']');
        codes.push(tab1 + '}');
        codes.push('});');

        return codes;
    },
    searchForm: function () {
        var tab1 = this.tab1, tab2 = this.tab2;
        var tab3 = this.tab3, tab4 = this.tab4;
        var codes = [], name = this.searchFormAllName;
        var fields = [];
        if (this.value.searchFromConfig && this.value.searchFromConfig.length > 0) {
            fields = this.value.searchFromConfig;
        }
        codes.push('Ext.define("' + name + '", { ');
        codes.push(tab1 + 'extend: "App.view.common.Form",');
        codes.push(tab1 + "xtype: '" + this.searchFormXtype + "',");
        codes.push(tab1 + "openEnterSearch:true,");
        codes.push(tab1 + '_mainConfs: ' + this.dataName + ',');
        codes.push(tab1 + '_confs: {');
        codes.push(tab2 + 'components: [//表单字段在这里配置');
        this.addCompToSearchForm(fields, codes, tab3, tab4);
        codes.push(tab2 + ']');
        codes.push(tab1 + '}');
        codes.push('});');

        return codes;
    },
    toolbar: function () {
        var tab1 = this.tab1, tab2 = this.tab2;
        var tab3 = this.tab3;
        var codes = [], name = this.toolbarAllName;
        codes.push('Ext.define("' + name + '", { ');
        codes.push(tab1 + 'extend: "App.view.common.Toolbar",');
        codes.push(tab1 + "xtype: '" + this.toolbarXtype + "',");
        codes.push(tab1 + '_confs: {');
        codes.push(tab2 + 'components: [//toolbar的组件在这里配置');
        codes.push(tab3 + "{name: 'c',actionObject:'" + this.windowAddXtype + "'},//处理方法_create");
        codes.push(tab3 + "{name: 'u',actionObject:'" + this.windowEditXtype + "'},//处理方法_update");
        codes.push(tab3 + "{name: 'd',actionUrl:'" + this.value.delUrl + "'}//处理方法_delete，actionUrl配置删除的请求地址");
        codes.push(tab2 + ']');
        codes.push(tab1 + '}');
        codes.push('});');

        return codes;
    },
    viewModel: function () {
        var tab1 = this.tab1, tab2 = this.tab2;
        var codes = [], name = this.viewModelAllName;
        codes.push('Ext.define("' + name + '", { ');
        codes.push(tab1 + 'extend: "App.view.BaseViewModel",');
        codes.push(tab1 + "alias: 'viewmodel." + this.viewModelXtype + "',");
        codes.push(tab1 + "data: {");
        codes.push(tab2 + "pageName: '" + this.className + "',");
        codes.push(tab2 + "'" + this.className + "-btnCreate': true,");
        codes.push(tab2 + "'" + this.className + "-btnUpdate': true,");
        codes.push(tab2 + "'" + this.className + "-btnDelete': true");
        codes.push(tab1 + "}");

        codes.push('});');

        return codes;
    },
    window: function () {
        var tab1 = this.tab1, tab2 = this.tab2;
        var codes = [], name = this.windowAllName;
        codes.push('Ext.define("' + name + '", { ');
        codes.push(tab1 + 'extend: "App.view.common.Window",');
        codes.push(tab1 + 'alias: "widget.' + this.windowXtype + '",');
        codes.push(tab1 + 'openValidation:true,');
        codes.push(tab1 + 'width: 600, // 窗口宽度');
        codes.push(tab1 + 'height: 400, // 窗口高度');
        codes.push(tab1 + "bodyPadding: '15px',");
        /*codes.push(tab1 + 'requires: [');
        codes.push(tab2 + '"' + this.windowAllName + '",');
        codes.push(tab2 + '"' + this.formAllName + '"');
        codes.push(tab1 + '],');*/
        codes.push(tab1 + 'items: [// 当items中对象配置的isParam为true时，当前window的提交操作会自动调用该对象的获取参数方法和isValid方法验证数据合法性');
        codes.push(tab2 + "//如果当前窗口对象的isGetChangeValue属性值为false（默认），items中form表单，调用getValues方法获取参数。如果是grid编辑列表，调用getEncodeValues方法获取参数");
        codes.push(tab2 + "//如果当前窗口对象的isGetChangeValue属性值为true，items中的form表单，调用getChangeValues方法获取参数。grid列表，getEncodeChangeValues方法获取参数");
        codes.push(tab2 + "//当items中对象配置autoSetSelect: true,如果窗口对象的_record属性存在，将会自动将_record中的数据赋值给items的对象");
        codes.push(tab2 + "{name: '" + this.formXtype + "', xtype: '" + this.formXtype + "', isParam: true, autoSetSelect: true}");
        codes.push(tab1 + ']');
        codes.push('});');

        return codes;
    },
    windowAdd: function () {
        var tab1 = this.tab1;
        var codes = [], name = this.windowAddAllName;
        codes.push('Ext.define("' + name + '", { ');
        codes.push(tab1 + 'extend: "' + this.windowAllName + '",');
        codes.push(tab1 + 'alias: "widget.' + this.windowAddXtype + '",');

        codes.push(tab1 + "buttons: [{name: 'submit', actionUrl: '" + this.value.addUrl + "'}, 'close']");
        codes.push('});');

        return codes;
    },
    windowEdit: function () {
        var tab1 = this.tab1;
        var codes = [], name = this.windowEditAllName;
        codes.push('Ext.define("' + name + '", { ');
        codes.push(tab1 + 'extend: "' + this.windowAllName + '",');
        codes.push(tab1 + 'alias: "widget.' + this.windowEditXtype + '",');
        codes.push(tab1 + "buttons: [{name: 'submit', actionUrl: '" + this.value.editUrl + "'}, 'close']");
        codes.push('});');

        return codes;
    },
    createFiles: function (value) {
        this.value = value;
        var me = this,
            path = value.path,
            type = value.type;

        this.submit(path, type, this.main(), this.className);
        setTimeout(function () {
            me.submit(path, type, me.form(), me.formName);
        }, 200);
        setTimeout(function () {
            me.submit(path, type, me.grid(), me.gridName);
        }, 400);
        setTimeout(function () {
            me.submit(path, type, me.searchForm(), me.searchFormName);
        }, 600);
        setTimeout(function () {
            me.submit(path, type, me.toolbar(), me.toolbarName);
        }, 800);
        setTimeout(function () {
            me.submit(path, type, me.viewModel(), me.viewModelName);
        }, 1000);
        setTimeout(function () {
            me.submit(path, type, me.window(), me.windowName);
        }, 1200);
        setTimeout(function () {
            me.submit(path, type, me.windowAdd(), me.windowAddName);
        }, 1400);
        setTimeout(function () {
            me.submit(path, type, me.windowEdit(), me.windowEditName);
        }, 1600);
        setTimeout(function () {
            me.submit(path, type, me.createDatas(), "Datas");
        }, 1800);
    },
    submit: function (path, type, codes, className) {
        var re = /\\/gi;
        path = path.replace(re, "\\\\");
        Ext.Ajax.request({
            url: 'fileGenerate',
            method: 'post',
            params: {
                codes: codes,
                className: className,
                path: path,
                type: type
            },
            success: function (response, opts) {
                var obj = Ext.decode(response.responseText);
                if (obj.success) {
                    App.ux.Toast.show('提示', '生成前端代码成功！','s');
                }
            },

            failure: function (response, opts) {
                console.log('server-side failure with status code ' + response.status);
            }
        });

    },
    //去除空格
    createFields: function (f) {
        var i;
        var value = f.replace(/\s+/g, "");
        if (value.substring(5).split('[').length > 0) {
            this.fields = eval(value);
        } else {
            this.fields = eval('[' + value + ']');
        }
    }
});